package com.mgg.auth.controller;

import com.mgg.auth.constant.SecurityConstants;
import com.mgg.common.client.message.MessageClient;
import com.mgg.common.entity.ValidateCode;
import com.mgg.auth.enums.AuthResultEnum;
import com.mgg.auth.properties.SecurityProperties;
import com.mgg.common.enums.SmsTypeEnum;
import com.mgg.common.util.ResultVOUtil;
import com.mgg.common.util.Tools;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lijun
 * @Date: 2018/9/3 15:13
 */
@RestController
public class LoginController {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private MessageClient messageClient;

    @GetMapping(value = "/hi")
    public Object hi() throws Exception {
        return "hi";
    }

    @GetMapping("/me")
    public Object getCurrentUser(@AuthenticationPrincipal UserDetails user) {
        return user;
    }


    /**
     * 创建验证码
     *
     * @param mobile
     * @throws Exception
     */
    @GetMapping("/code/sms")
    public Object createCode(@RequestParam String mobile)
            throws Exception {
        if (StringUtils.isBlank(mobile)) {
            return ResultVOUtil.error(AuthResultEnum.SMSCODE_PHONE_NONE_ERROR.getCode(),AuthResultEnum.SMSCODE_PHONE_NONE_ERROR.getMessage());
        }
        if (!Tools.checkMobileNumber(mobile)) {
            return ResultVOUtil.error(AuthResultEnum.SMSCODE_PHONE_CHECK_ERROR.getCode(),AuthResultEnum.SMSCODE_PHONE_CHECK_ERROR.getMessage());
        }

        String key = "code:sms:" + mobile;
        String key1 = key + ":num";
        ValidateCode validateCode = (ValidateCode) redisTemplate.opsForValue().get(key);
        if (validateCode != null) {
            LocalDateTime limitTime = validateCode.getExpireTime().minusSeconds(securityProperties.getCode().getSms().getExpireIn()-60);
            if(limitTime.isAfter(LocalDateTime.now())) {
                return ResultVOUtil.error(AuthResultEnum.PHONE_SMSCODE_SEND_TIME_ERROR.getCode(), AuthResultEnum.PHONE_SMSCODE_SEND_TIME_ERROR.getMessage());
            }
        }
        Integer num = 0;
        if (redisTemplate.hasKey(key1)) {
            num = (Integer) redisTemplate.opsForValue().get(key1);
        }
        if (num >= 10) {
            return ResultVOUtil.error(AuthResultEnum.PHONE_SMSCODE_NUM_ERROR.getCode(), AuthResultEnum.PHONE_SMSCODE_NUM_ERROR.getMessage());
        }

        String code = RandomStringUtils.randomNumeric(securityProperties.getCode().getSms().getLength());
        ValidateCode newCode = new ValidateCode(code, securityProperties.getCode().getSms().getExpireIn());
        redisTemplate.opsForValue().set(key,newCode);
        String param = "{\"code\":\"" + code + "\"}";
        messageClient.sendSms(SmsTypeEnum.VALIDATECODE.getSmsType(),SmsTypeEnum.VALIDATECODE.getSubType(),mobile,param);

        num += 1;
        if (num == 1) {
            redisTemplate.opsForValue().set(key1, num, 24, TimeUnit.HOURS);
        } else {
            redisTemplate.opsForValue().set(key1, num, redisTemplate.getExpire(key1), TimeUnit.SECONDS);
        }
        Map<String,String> result = new HashMap<>();
        result.put("message", "发送成功，24小时内还可以发送 " + (10-num) + "次");
        return ResultVOUtil.success(result);
    }

    @GetMapping(SecurityConstants.LOGIN_PROCESSING_URL_MOBILE)
    public Object loginWithMobile() {
        return ResultVOUtil.success();
    }

    @PostMapping(SecurityConstants.LOGIN_PROCESSING_URL_OPENID)
    public Object loginWithOpenid() {
        return ResultVOUtil.success();
    }
}